package com.aisb.core.util;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class RequestUtil {

	/**
	 * 
	 * @Description : 获取用户IP
	 * 
	 * @return String
	 *
	 * @author : wucm
	 * @date : 2016年4月13日 下午5:32:17
	 *
	 */
	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 
	 * @Description : 根据IP解析地址
	 * 
	 * @return String
	 *
	 * @author : wucm
	 * @date : 2016年7月21日 下午2:28:19
	 *
	 */
	public static String getAddressByIP(String strIP) {
		if (null == strIP || "127.0.0.1".equals(strIP)
				|| "localhost".equals(strIP) || strIP.startsWith("192.")) {
			return "";
		}

		try {
			URL url = new URL(
					"http://ip.taobao.com/service/getIpInfo.php?ip=" + strIP);
			URLConnection conn = url.openConnection();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(conn.getInputStream(), "GBK"));
			String line = null;
			StringBuffer result = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				result.append(line);
			}
			reader.close();
			String rstr = result.toString();

			JSONObject j = JSONObject.parseObject(rstr);
			if (null != j) {
				if ("0".equals(j.getString("code"))) {
					JSONObject jd = j.getJSONObject("data");
					if (null != jd) {
						String country = jd.getString("country");
						String region = jd.getString("region");
						String city = jd.getString("city");
						String isp = jd.getString("isp");
						String s = region + " " + city + " [" + isp + "]";
						return s;
					}
				}
			} else {
				rstr = "";
			}

			return "";
		} catch (IOException e) {
			return "";
		}
	}

	public static void main(String[] args) {

	}

}
